package Controller.CourseServlet;

import Dao.CourseDao;
import bean.Course;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/course_add")
public class course_add extends HttpServlet {
    CourseDao courseDao = new CourseDao();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String cname = req.getParameter("cname");
        String cno = req.getParameter("cno");
        String ctime = req.getParameter("ctime");
        String quota = req.getParameter("quota");
        String credit = req.getParameter("credit");
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        Course c1 = courseDao.selectByCno(cno);
        Course c2 = courseDao.selectByCname(cname);
        if (c1 != null) {
            map.put("msg", "课程号已存在!");
            map.put("code", 400);
        } else if (c2 != null) {
            map.put("msg", "课程名已存在!");
            map.put("code", 400);
        } else {
            map.put("msg", "添加成功!");
            courseDao.insert(cno, cname, credit, ctime, quota);
        }
        resp.getWriter().write(JSON.toJSONString(map));
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
